package org.sang.filter;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.sang.utils.CheckResult;
import org.sang.utils.TokenMgr;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import java.io.IOException;
import java.util.List;

@Component
public class JwtFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String tokenStr = servletRequest.getParameter("token");
        // 验证JWT的签名，返回CheckResult对象
        if (StringUtils.isNotBlank(tokenStr)) {
            CheckResult checkResult = TokenMgr.validateJWT(tokenStr);
            if (checkResult.isSuccess()) {
                Claims claims = checkResult.getClaims();
                String username = claims.getSubject();
                List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));
                UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(token);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}